package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2022/07/08 10:24
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;
    //@Autowired
    //SqlSessionFactory sqlSessionFactory;

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public void transfer(int fromId, int destId, int money) {
        //SqlSession sqlSession = sqlSessionFactory.openSession();
        //accountMapper = sqlSession.getMapper(AccountMapper.class);

        // 使用accountMapper执行转账业务
        int fromMoney = accountMapper.selectMoneyById(fromId);
        int destMoney = accountMapper.selectMoneyById(destId);

        fromMoney -= money;
        destMoney += money;

        // 匿名内部类的写法
        int finalFromMoney = fromMoney;
        int finalDestMoney = destMoney;

        // transactionTemplate执行方法是为了增加事务
        // 增加事务的过程中需要使用到两个对象：TransactionManager、TransactionCallBack
        // TransactionManager在注册组件的时候就已经提供了
        // TransactionCallBack是在执行方法的时候传入的对象
        // execute方法是为了给doInTransaction方法中的内容增加事务
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                // 发生异常的情况，事务提交了
                accountMapper.updateMoneyById(fromId, finalFromMoney);
                // 制造异常
                int i = 1 / 0;
                accountMapper.updateMoneyById(destId, finalDestMoney);
                return null;
            }
        });

        /*// 发生异常的情况，事务提交了
        accountMapper.updateMoneyById(fromId, fromMoney);
        // 制造异常
        int i = 1 / 0;
        accountMapper.updateMoneyById(destId, destMoney);*/

    }
}
